import React from 'react';
import { observer, inject } from 'mobx-react';
import { routerShape } from 'react-router';
import allStore from '../../stores';
import { WeaTools,WeaErrorPage,WeaRightMenu,WeaTop,WeaLeftRightLayout,WeaDropdown,WeaLocaleProvider } from 'ecCom';
import { Button } from 'antd';
import * as mobx from 'mobx';
import QueryList from './QueryList';
import LeftTree from './LeftTree';
import Condition from './Condition';
import { WeaTableNew } from 'comsMobx';
const WeaTable = WeaTableNew.WeaTable;
import BatchSubmit from '../../asyncComps/BatchSubmit';
import { doBatchSubmit } from '../../apis/list';
import BatchShare from '../../asyncComps/BatchShare';
import {Synergy} from 'weaPortal';
import TagTypeSelectDialog from "../../asyncComps/TagTypeSelectDialog";
import {verifySupervise} from "../../util/superviseUtil";
const getLabel = WeaLocaleProvider.getLabel;

@inject("wfQueryResultStore")
@observer
class QueryResult extends React.Component{
    static contextTypes = {
        router: routerShape
    }
    constructor(){
        super();
    }

    varTemp = {
      text: getLabel(21223,'督办'),
      btns: [],
      rightBtns: [],
      batchShareids: []
    }
    doInit(props){
        const { wfQueryResultStore,location } = props;
        wfQueryResultStore.resetAllStatus();
        const urlParams = location.query || {};
        const fromwhere = urlParams.fromwhere || "queryIndex";
        const formIndex = fromwhere === "queryIndex";
        wfQueryResultStore.setUrlParams(urlParams);
        wfQueryResultStore.setShowTreeSwitch(formIndex);
        if(formIndex){
            if(window.location.href.indexOf('notneedTab') < 0) {
              wfQueryResultStore.initTopTab();
            }
            wfQueryResultStore.copyQueryIndexStore(allStore.wfQueryIndexStore);
            wfQueryResultStore.doSearch();
        }else{  //urlFilter通过url参数过滤数据、jsonFilter门户More通过json串过滤数据
            if(fromwhere === "urlFilter" && window.location.href.indexOf('notneedTab') < 0) {
              wfQueryResultStore.initTopTab();
            }
            wfQueryResultStore.doInit(()=>{
                wfQueryResultStore.doSearch();
            });
        }
    }
    componentDidMount(){
        this.doInit(this.props);
        const { wfQueryResultStore } = this.props;
        if(window.location.pathname.indexOf('/spa/workflow/index') > -1)
            document.title = wfQueryResultStore.title;
        _ListenerCtrl.bind();
        // const { hover } = this.props.wfQueryResultStore;
        this.timerID=setTimeout(()=>{ 
            $(".wf_attention_div_btn").on("mouseover mouseout",function(event){
                const str = $(this).attr('id').substr($(this).attr('id').indexOf('_'))
                if(event.type == "mouseover"){  
                 jQuery("#attentionSpan"+str).css("display","block")
                }else if(event.type == "mouseout"){
                 jQuery("#attentionSpan"+str).css("display","none")
                }
               })
         },1000)
    }
    componentWillReceiveProps(nextProps) {
        if(this.props.location.key !== nextProps.location.key)  //快捷搜索变换内容触发
        	this.doInit(nextProps);
    }
    componentDidUpdate(){
        // const { hover } = this.props.wfQueryResultStore;
        this.timerID=setTimeout(()=>{ 
            $(".wf_attention_div_btn").on("mouseover mouseout",function(event){
            const str = $(this).attr('id').substr($(this).attr('id').indexOf('_'))
            if(event.type == "mouseover"){  
             jQuery("#attentionSpan"+str).css("display","block")
            }else if(event.type == "mouseout"){
             jQuery("#attentionSpan"+str).css("display","none")
            }
           }) },1000)
      }
    componentWillUnmount(){
        const { wfQueryResultStore } = this.props;
        wfQueryResultStore.resetAllStatus();
        _ListenerCtrl.unbind();
        clearTimeout(this.timerID);
    }
    render(){
        const { wfQueryResultStore } = this.props;
        const { title,loading,urlParams,tableStore,fixedForm,showSearchAd,showModalObj,detailTitle,hasScrollX,showBatchSupervisor } = wfQueryResultStore;
        const topTitle = title+detailTitle;
        const contentDiv = <QueryList ecId={`${this && this.props && this.props.ecId || ''}_QueryList@isqy8s`} needInit={false} />;
        const WeaTopContent = urlParams.needTree === "false" ?
            <div>{contentDiv}</div> :
            <WeaLeftRightLayout ecId={`${this && this.props && this.props.ecId || ''}_WeaLeftRightLayout@byll7o`}
                leftCom={<LeftTree ecId={`${this && this.props && this.props.ecId || ''}_LeftTree@q16xql`} queryStore={wfQueryResultStore} />}
                defaultShowLeft={true}
            >{contentDiv}</WeaLeftRightLayout>;
            this.varTemp.btns = [];
            this.varTemp.btns = this.getTopButtons();
            this.varTemp.rightBtns = this.varTemp.batchShareids = [];
            this.varTemp.rightBtns = this.getRightMenu();
            this.varTemp.batchShareids = tableStore.selectedRowKeys;
        return (
            <div className="wf-query-result">
                <WeaRightMenu ecId={`${this && this.props && this.props.ecId || ''}_WeaRightMenu@16bez9`} 
                    collectParams={{favname:title, favouritetype:2}}
                    datas={this.varTemp.rightBtns}
                >
                    <WeaTop ecId={`${this && this.props && this.props.ecId || ''}_WeaTop@0b9gbt`}
                        title={topTitle}
                        loading={loading || tableStore.loading}
                        icon={<i className='icon-coms-workflow' />}
                        iconBgcolor='#0079DE'
                        buttons={this.varTemp.btns}
                        buttonSpace={10}
                        showDropIcon={true}
                        dropMenuDatas={this.varTemp.rightBtns}
                    >
                        {WeaTopContent}
                    </WeaTop>
                    <BatchShare ecId={`${this && this.props && this.props.ecId || ''}_BatchShare@36odsz`}
                        visible={showModalObj.batchShare || false}
                        controlModal={this.controlModal}
                        // ids={tableStore.selectedRowKeys}
                        ids={this.varTemp.batchShareids}
                    />
                    <BatchSubmit ecId={`${this && this.props && this.props.ecId || ''}_BatchSubmit@43vy6d`} 
                        visible={showModalObj.batchSubmit || false}
                        onSubmit={this.batchSubmitEvent}
                        onCancel={this.batchCancel}
                    />
                </WeaRightMenu>
                <Synergy ecId={`${this && this.props && this.props.ecId || ''}_Synergy@82bhz6`} pathname='/workflow/queryFlowResult' requestid="-1" />

                <BatchSubmit ecId={`${this && this.props && this.props.ecId || ''}_BatchSubmit@3ryoxu`}
                        visible={showBatchSupervisor}
                        onSubmit={this.batchSupervisorEvent}
                        onCancel={this.cancel}
                        onSubmitText={this.varTemp.text}
                    />
                <TagTypeSelectDialog ecId={`${this && this.props && this.props.ecId || ''}_TagTypeSelectDialog@h014c8`} curStore={allStore.wfFollowTypeSettingStore} refresh={wfQueryResultStore.doSearch}/>
            </div>
        )
    }
    controlModal = v =>this.props.wfQueryResultStore.controlShowModal("batchShare", v);
    batchCancel = () =>{this.props.wfQueryResultStore.controlShowModal("batchSubmit", false)};
    cancel = ()=>{wfQueryResultStore.setShowBatchSupervisor(false)};
    // returnQueryIndex(){     //返回到查询导航页面
    //     this.context.router.push({pathname:"/main/workflow/queryFlow?fromwhere=queryResult"});
    // }
    getTopButtons(){
        const { wfQueryResultStore } = this.props;
        const { tableStore,viewcondition,operBtnKey,loading } = wfQueryResultStore;
        const selectedRowKeys = tableStore.selectedRowKeys;
        const btndatas = [
            {key:"batchShare", show:getLabel(18037,"批量共享"), selected: operBtnKey === "batchShare"},
            {key:"batchSubmit", show:getLabel(17598,"批量提交"), selected: operBtnKey === "batchSubmit"},
            { key:"batchAttention", show: getLabel(503955,"批量关注"), selected: operBtnKey === "batchAttention"}
            //{ key:"batchSupervisor",show: getLabel(84561,"批量督办"), selected: operBtnKey === "batchSupervisor" }
        ];
        let btns =[];
        if(viewcondition === 0||viewcondition ===2){
            const { ButtonSelect } = WeaDropdown;
            btns.push(<ButtonSelect ecId={`${this && this.props && this.props.ecId || ''}_ButtonSelect@rhn69h@${viewcondition}`} datas={btndatas}
                btnProps={{disabled:selectedRowKeys.length <= 0 || loading}}
                dropdownProps={{trigger:['click']}}
                dropBtnProps={{title:getLabel(384039,"点击切换批量操作")}}
                btnOnClick={key =>{
                    if(key === "batchShare")
                        this.batchShareClick(selectedRowKeys);
                    else if(key === "batchSubmit")
                        this.batchSubmitClick();
                    else if(key === "batchSupervisor")
                        this.batchSupervisor();
                    else if(key === "batchAttention")
                        this.batchAttention();
                }}
                menuOnClick={(key, e) =>{
                    wfQueryResultStore.clickButttonDrop(key);
                }}
            />);
        }
        return btns;
    }
    getRightMenu(){
        const { wfQueryResultStore } = this.props;
        const { tableStore,operBtnKey,viewcondition,loading } = wfQueryResultStore;
        const selectedRowKeys = tableStore.selectedRowKeys;
    	let btns = [];
    	btns.push({
            key: "search",
    		icon: <i className='icon-workflow-Right-menu--search'/>,
            content: getLabel(197,'搜索'),
            onClick: key =>{
                wfQueryResultStore.doSearch();
            }
        });
        if(viewcondition === 0||viewcondition === 2){
            btns.push({
                key: "batchSubmit",
                icon: <i className='icon-workflow-Right-menu-batch'/>,
                content: getLabel(17598,"批量提交"),
                disabled: operBtnKey !== "batchSubmit" || selectedRowKeys.length <= 0,
                onClick: this.batchSubmitClick
            });
            btns.push({
                key: "batchShare",
                icon: <i className='icon-workflow-Right-menu-Batch-sharing'/>,
                content: getLabel(18037,"批量共享"),
                disabled: operBtnKey !== "batchShare" || selectedRowKeys.length <= 0 || loading,
                onClick: this.batchShareClick.bind(this,selectedRowKeys)
            });
            btns.push({
                key: "batchAttention",
                icon: <i className='icon-coms-Subscribe'/>,
                content: getLabel(503955,'批量关注'),
                disabled: operBtnKey !== "batchAttention" || selectedRowKeys.length <= 0,
                onClick: this.batchAttention.bind(this,selectedRowKeys)
            });
            /*btns.push({
                key: "batchSupervisor",
                icon: <i className='icon-coms-daiban'/>,
                content: getLabel(84561,'批量督办'),
                disabled: operBtnKey !== "batchSupervisor" || selectedRowKeys.length <= 0,
                onClick: this.batchSupervisor.bind(this)
            });*/
        }
        btns.push({
            key: "colSet",
    		icon: <i className='icon-workflow-Right-menu-Custom'/>,
            content: getLabel(32535,'显示列定制'),
            onClick: key =>{
                tableStore.setColSetVisible(true);
    		        tableStore.tableColSet(true);
            }
    	});
    	return btns;
    }
    batchShareClick = (selectedRowKeys) => {
        const { wfQueryResultStore } = this.props;
        wfQueryResultStore.controlShowModal("batchShare", true);
    }
    batchSubmitClick = () => {
        const { wfQueryResultStore } = this.props;
        const { otherInfo } = wfQueryResultStore;
		if(otherInfo.multisubmitnotinputsign == "1")     //弹窗输入签字意见
            wfQueryResultStore.controlShowModal("batchSubmit", true);
		else
			this.batchSubmitEvent("");
    }

    batchSupervisorEvent = (remark = '') => {
        const { wfQueryResultStore } = this.props;
        const { tableStore } = wfQueryResultStore;
        const selectedRowKeys = tableStore.selectedRowKeys;


        let requestids = selectedRowKeys;

        let params = {requestids,remark};
        verifySupervise(requestids,remark,()=> {
            wfQueryResultStore.doSupervise(params);
            wfQueryResultStore.setShowBatchSupervisor(false);
        });
    }

    //批量督办
    batchSupervisor = () => {
        const { wfQueryResultStore } = this.props;
        wfQueryResultStore.setShowBatchSupervisor(true);
    }

    //批量关注
    batchAttention = () => {
        const { wfQueryResultStore } = this.props;
        const { sharearg ,tableStore} = wfQueryResultStore;
        const {selectedRowKeys} = tableStore;
        let idarr = selectedRowKeys.map(v => {
            const arr = v.split("_");
            const requestid = arr[0];
            return requestid;
        });
        let requestIds = idarr.join(",");
        
        allStore.wfFollowTypeSettingStore.isSingle = false
        allStore.wfFollowTypeSettingStore.followTypeSelectShow = true
        allStore.wfFollowTypeSettingStore.FollowRequestid = requestIds
        if(idarr.length==1){
            window.followTypeSettingStore.getWorkflowAttentionTypeSet(idarr[0])
        }else{
            window.followTypeSettingStore.getWorkflowAttentionTypeSet()
        }
    }
    
    batchSubmitEvent = (remark) => {
        const { wfQueryResultStore } = this.props;
        const { tableStore } = wfQueryResultStore;
        wfQueryResultStore.setLoading(true);
		doBatchSubmit(remark, tableStore.selectedRowKeys, []).then(data => {
            wfQueryResultStore.setLoading(false);
            wfQueryResultStore.reLoad();
            tableStore.tableUpdate({selectedRowKeys:[]});
        });
        wfQueryResultStore.controlShowModal("batchSubmit", false);
    }
}

export default WeaTools.tryCatch(React, 
    props => <WeaErrorPage ecId={`${this && this.props && this.props.ecId || ''}_WeaErrorPage@4lany8`} msg={ props.error ? props.error : getLabel(383324,' 对不起，该页面异常，请联系管理员 ')+'！'} />,
    {error: ""}
)(QueryResult);